package dm.service;

import java.util.ArrayList;
import java.util.List;
import javax.swing.event.EventListenerList;
import dm.ui.MyTableRow;

public class DownloadService extends Thread implements URLListener
{
	URLObject m_firstURL;
	String saveIn;	
	
	MyTableRow pbar;
	List<URLObject> m_urls = new ArrayList<URLObject>();
	
	double totalSize = 0;
	long totalFiles = 0;
	protected EventListenerList m_eList = new EventListenerList();	
	
	
	public DownloadService(URLObject ro, String si, MyTableRow bar)
	{
		this.m_firstURL = ro;
		
		m_urls.add(m_firstURL);		
		saveIn = si;		
		pbar = bar;
		this.setPriority(MIN_PRIORITY);
				
	}//end constructor
		
	public void run()
	{
		int i = 0;
		try
		{	
			//while(!isCompleted())
			while(true)
			{
				synchronized(m_urls)
				{
					for(i=0;i<m_urls.size();i++)
					{
						if(m_urls.get(i) != null && m_urls.get(i).getStatus() == URLObject.WAITING)
						{
							//m_urls.get(i).setStatus(URLObject.FINISHED);
							DownloadThread dt = new DownloadThread(m_urls.get(i), m_urls, saveIn);
							dt.start();
						}
					}
				}
				//System.out.println(m_urls.size());
				//calculatePercenComplete();
				//da synchronized trong ham isComplete roi
				//if(isCompleted())
					//return;
			}			
				        
		}catch(Exception ex)
		{			
			System.out.println("[DownloadService.run] ERROR: " + i + " / " + m_urls.size());
			ex.printStackTrace();			
		}		
	}//end run	
		
	private void calculatePercenComplete()
	{
		int i;
		int c = 0;
		int pc = 0;
		synchronized(m_urls)
		{
			for(i=0; i<this.m_urls.size(); i++)
			{
				if(m_urls.get(i).getStatus() == URLObject.FINISHED)
					c++;
			}
			
			pc = c*100/m_urls.size();
			pbar.getPbar().setValue(pc);
			pbar.setTotalSize((long)totalSize);
			pbar.setNumOfFile(totalFiles);
			
			// TODO Auto-generated method stub		
			Object[] listeners = m_eList.getListenerList();
			
			// loop through each listener and pass on the event if needed
		    int numListeners = listeners.length;
		    for (i = 0; i<numListeners; i+=2) 
		    {
		    	if (listeners[i] == URLListener.class) 
		        {
		    		// pass the event to the listeners event dispatch method
		        	((URLListener)listeners[i+1]).Finished("Update");
		        }            
		     }
			
			//System.out.println(" [calculatePercenComplete] Complete / Total = " + c + "/" + m_urls.size());
		}
	}
	
	private boolean isCompleted()
	{
		calculatePercenComplete();
		synchronized(m_urls)
		{
			int i;			
			
			for(i=0;i<m_urls.size();i++)
        	{
        		if(m_urls.get(i).getStatus() != URLObject.FINISHED)
        		{        			
        			return false;
        		}
        	}			
			return true;
		}
	}
	
	
	public void addURLListener(URLListener listener)
	{
		m_eList.add(URLListener.class, listener);
	}
	
	public void removeChessItemListener(URLListener listener)
	{
		m_eList.remove(URLListener.class, listener);
	}

	public void Finished(String msg)
	{
		// TODO Auto-generated method stub		
	}

	public void getNewURL(URLObject obj, String saveIn) {
		// TODO Auto-generated method stub
		
	}
}
